<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- 常用搜索条件 -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="PersonId_FormItem" prop="PersonId">
							<template #label>
								<WtmLabelTooltip label="员工" tooltip="关联的员工实体" />
							</template>
							<el-select v-model="searchData.PersonId" :data="stateData.AllSysPersons" clearable>
								<el-option v-for="item in stateData.AllSysPersons" :key="item.Value" :value="item.Value" :label="item.Text"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="ProfessionalTitleTypeId_FormItem" prop="ProfessionalTitleTypeId">
							<template #label>
								<WtmLabelTooltip label="资质类别" tooltip="关联的职称类别" />
							</template>
							<el-select v-model="searchData.ProfessionalTitleTypeId" :data="stateData.AllSysPersonProfessionalTitleTypes" clearable>
								<el-option
									v-for="item in stateData.AllSysPersonProfessionalTitleTypes"
									:key="item.Value"
									:value="item.Value"
									:label="item.Text"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="QualificationName_FormItem" prop="QualificationName">
							<template #label>
								<WtmLabelTooltip label="资质名称" tooltip="资质的具体名称" />
							</template>
							<el-input v-model="searchData.QualificationName" clearable></el-input>
						</el-form-item>
					</el-col>

					<!-- 可展开的详细搜索条件 -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="QualificationLevel_FormItem" prop="QualificationLevel">
								<template #label>
									<WtmLabelTooltip label="资质等级" tooltip="资质等级（如：国家级/省级/市级/区县级）" />
								</template>
								<el-select v-model="searchData.QualificationLevel" clearable>
									<el-option key="高级" value="高级" label="高级"></el-option>
									<el-option key="中级" value="中级" label="中级"></el-option>
									<el-option key="初级" value="初级" label="初级"></el-option>
									<el-option key="国家级" value="国家级" label="国家级"></el-option>
									<el-option key="省级" value="省级" label="省级"></el-option>
									<el-option key="市级" value="市级" label="市级"></el-option>
									<el-option key="区县级" value="区县级" label="区县级"></el-option>
									<el-option key="正高级" value="正高级" label="正高级"></el-option>
									<el-option key="副高级" value="副高级" label="副高级"></el-option>
									<el-option key="助理级" value="助理级" label="助理级"></el-option>
									<el-option key="员级" value="员级" label="员级"></el-option>
									<el-option key="特级" value="特级" label="特级"></el-option>
									<el-option key="一级" value="一级" label="一级"></el-option>
									<el-option key="二级" value="二级" label="二级"></el-option>
									<el-option key="三级" value="三级" label="三级"></el-option>
									<el-option key="四级" value="四级" label="四级"></el-option>
									<el-option key="五级" value="五级" label="五级"></el-option>
									<el-option key="其他" value="其他" label="其他"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="IssuingAuthority_FormItem" prop="IssuingAuthority">
								<template #label>
									<WtmLabelTooltip label="发证单位" tooltip="颁发证书的机构" />
								</template>
								<el-input v-model="searchData.IssuingAuthority" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="CertificateCode_FormItem" prop="CertificateCode">
								<template #label>
									<WtmLabelTooltip label="证书编码" tooltip="证书的唯一编码" />
								</template>
								<el-input v-model="searchData.CertificateCode" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="ObtainedDate_FormItem" prop="ObtainedDate">
								<template #label>
									<WtmLabelTooltip label="获得日期" tooltip="获得资质的日期" />
								</template>
								<el-date-picker v-model="searchData.ObtainedDate" clearable></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="ExpiryDate_FormItem" prop="ExpiryDate">
								<template #label>
									<WtmLabelTooltip label="有效期" tooltip="资质的有效期" />
								</template>
								<el-date-picker v-model="searchData.ExpiryDate" clearable></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="SalaryReward_FormItem" prop="SalaryReward">
								<template #label>
									<WtmLabelTooltip label="薪资奖励" tooltip="与资质相关的薪资或奖励信息" />
								</template>
								<el-input-number v-model="searchData.SalaryReward" clearable></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="Remark_FormItem" prop="Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="额外说明信息" />
								</template>
								<el-input v-model="searchData.Remark" clearable></el-input>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysPersonProfessionalTitle/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysPersonProfessionalTitle/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysPersonProfessionalTitle/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysPersonProfessionalTitle/SysPersonProfessionalTitleExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysPersonProfessionalTitle/Edit'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysPersonProfessionalTitle/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysPersonProfessionalTitle/BatchDelete'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="荣誉职称;true;HengTong.Areas.Person.Controllers;SysPersonProfessionalTitle">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysPersonProfessionalTitleApi as api } from '/@/views/person/syspersonprofessionaltitle/api';
import { ISysPersonProfessionalTitleView, ISysPersonProfessionalTitleQuery } from '/@/views/person/syspersonprofessionaltitle/api/interface';
import other from '/@/utils/other';
import { IViewModel, ISysSelectType } from '/@/types/common';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysPersonProfessionalTitleQuery;
		/** 主表ID */
		personId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		personId: null,
	}
);

const stateData = reactive({
	AllSysPersons: [] as ISysSelectType[],
	AllSysPersonProfessionalTitleTypes: [] as ISysSelectType[],
});

const searchData = ref<ISysPersonProfessionalTitleQuery>({
	PersonId: null,
	ProfessionalTitleTypeId: null,
	QualificationName: null,
	QualificationLevel: null,
	IssuingAuthority: null,
	CertificateCode: null,
	ObtainedDate: null,
	ExpiryDate: null,
	SalaryReward: null,
	Remark: null,
});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）s
	data: [],
	// 表头内容（必传，注意格式）
	header: [
		{ title: '员工', key: 'PersonName', type: 'text', isCheck: true },
		{ title: '资质类别', key: 'ProfessionalTitleTypeName', type: 'text', isCheck: true },
		{ title: '资质名称', key: 'QualificationName', type: 'text', isCheck: true },
		{ title: '资质等级', key: 'QualificationLevel', type: 'text', isCheck: true },
		{ title: '发证单位', key: 'IssuingAuthority', type: 'text', isCheck: true },
		{ title: '证书编码', key: 'CertificateCode', type: 'text', isCheck: true },
		{ title: '获得日期', key: 'ObtainedDate', type: 'text', isCheck: true },
		{ title: '有效期', key: 'ExpiryDate', type: 'text', isCheck: true },
		// { title: '薪资奖励', key: 'SalaryReward', type: 'text', isCheck: true },
		{ title: '证书文件', key: 'CertificateDocumentId', type: 'file', isCheck: true },
		{ title: '备注', key: 'Remark', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	const data = props.personId ? { PersonId: props.personId } : null;
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, data, getTableData, '50%');
};

const OnEditRowClick = (row: ISysPersonProfessionalTitleView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData, '50%');
};

const OnDetailsRowClick = (row: ISysPersonProfessionalTitleView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData, '50%');
};

// 删除
const onDelete = (row: ISysPersonProfessionalTitleView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysPersonProfessionalTitleView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	// 如果有personId，自动设置搜索条件
	if (props.personId) {
		searchData.value.PersonId = props.personId;
	}
	const promises: Promise<any>[] = [
		other.getSelectList('/api/SysPersonProfessionalTitle/GetSysPersons', [], false).then((x) => (stateData.AllSysPersons = x)),
		other
			.getSelectList('/api/SysPersonProfessionalTitle/GetSysPersonProfessionalTitleTypes', [], false)
			.then((x) => (stateData.AllSysPersonProfessionalTitleTypes = x)),

		getTableData(),
	];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>
